﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GTA.UserControls.Tools
{
    public partial class UcAlerts : BaseUserControl
    {
        #region Local Objects
        private List<BusinessEntity.Configuration.Alert> alerts;
        #endregion

        #region Starting Control
        public UcAlerts()
        {
            InitializeComponent();
        }
        private void UcAlerts_Load(object sender, EventArgs e)
        {
            StartControl();
        }
        private void StartControl()
        {
            LoadCurrentAlerts();
        }
        #endregion

        #region Events
        private void cmdNew_Click(object sender, EventArgs e)
        {
            CreateNewAlert();
        }
        private void cmdEdit_Click(object sender, EventArgs e)
        {
            EditSelectedAlert();
        }
        private void cmdDelete_Click(object sender, EventArgs e)
        {
            DeleteSelectedAlert();
        }
        private void lstAlerts_Resize(object sender, EventArgs e)
        {
            lstAlerts.Columns[1].Width = lstAlerts.Width - lstAlerts.Columns[0].Width - lstAlerts.Columns[2].Width - lstAlerts.Columns[3].Width - lstAlerts.Columns[4].Width - 23;
        }
        private void editarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EditSelectedAlert();
        }
        private void excluirToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeleteSelectedAlert();
        }
        private void ativoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UpdateAlertState(BusinessEntity.Configuration.AlertState.Ativo);
        }
        private void inativoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UpdateAlertState(BusinessEntity.Configuration.AlertState.Inativo);
        }
        private void criarNovoAlertaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateNewAlert();
        }
        private void lstAlerts_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            SortList(lstAlerts, GetListAlertsColumnType(e.Column), ref columnOrder, ref sortOrder, e.Column);
        }
        private void lstAlerts_DoubleClick(object sender, EventArgs e)
        {
            EditSelectedAlert();
        }
        private void lstAlerts_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
                DeleteSelectedAlert();
        }
        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            HandleContextMenuItemsState();
        }
        private void minutosToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetAlertSleep(GTA.BusinessEntity.Configuration.AlertSleepType.FiveMinutes);
        }
        private void minutosToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SetAlertSleep(GTA.BusinessEntity.Configuration.AlertSleepType.TenMinutes);
        }
        private void minutosToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            SetAlertSleep(GTA.BusinessEntity.Configuration.AlertSleepType.FifteenMinutes);
        }
        private void minutosToolStripMenuItem3_Click(object sender, EventArgs e)
        {
            SetAlertSleep(GTA.BusinessEntity.Configuration.AlertSleepType.ThirtyMinutes);
        }
        private void horaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetAlertSleep(GTA.BusinessEntity.Configuration.AlertSleepType.OneHour);
        }
        private void diaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetAlertSleep(GTA.BusinessEntity.Configuration.AlertSleepType.OneDay);
        }
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            SetSpecificPauseDate();
        }
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            DisablePause();
        }
        #endregion

        #region Methods
        private OrdenacaoListView.Tipo GetListAlertsColumnType(int column)
        {
            switch (column)
            {
                case 0:
                    return OrdenacaoListView.Tipo.Numerica;
                case 1:
                    return OrdenacaoListView.Tipo.Alfabetica;
                case 2:
                    return OrdenacaoListView.Tipo.Alfabetica;
                case 3:
                    return OrdenacaoListView.Tipo.Alfabetica;
                case 5:
                    return OrdenacaoListView.Tipo.Data;
                default:
                    return OrdenacaoListView.Tipo.Alfabetica;
            }
        }
        private void CreateNewAlert()
        {
            if (!Program.CheckOpenedWindow<FrmAlert>(true))
            {
                FrmAlert wd = new FrmAlert(null);
                wd.ShowInTaskbar = false;
                wd.ShowDialog(this);
                LoadCurrentAlerts();
            }
        }
        public void LoadCurrentAlerts()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                BusinessLogic.Configuration bl = new GTA.BusinessLogic.Configuration();
                alerts = bl.ListAlerts(Program.LoggedUser, null);
                lstAlerts.Items.Clear();
                if (alerts != null && alerts.Count > 0)
                {
                    foreach (BusinessEntity.Configuration.Alert item in alerts)
                    {
                        ListViewItem listItem = new ListViewItem(item.ID.ToString());
                        listItem.SubItems.Add(item.Name);
                        listItem.SubItems.Add(GetNotificationTypeDescription(item.AlertNotificationTypeList));
                        listItem.SubItems.Add(item.State.ToString());
                        listItem.SubItems.Add(item.SleepDate != DateTime.MinValue ? item.SleepDate.ToString(DATE_FORMAT_FULL) : String.Empty);
                        lstAlerts.Items.Add(listItem);
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException("Carregar os alertas existentes.", ex);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        private string GetNotificationTypeDescription(List<BusinessEntity.Configuration.NotificationType> list)
        {
            StringBuilder description = new StringBuilder();
            if (list != null && list.Count > 0)
                list.ForEach(it => description.Append(it + " - "));
            if (!String.IsNullOrEmpty(description.ToString()))
                description.Remove(description.Length - 2, 2);
            return description.ToString();
        }
        private void EditSelectedAlert()
        {
            try
            {
                if (lstAlerts.SelectedItems.Count == 1)
                {
                    Cursor = Cursors.WaitCursor;
                    FrmAlert wd = new FrmAlert(alerts.Find(it => it.ID.CompareTo(Convert.ToInt32(lstAlerts.SelectedItems[0].SubItems[0].Text)) == 0));
                    wd.ShowInTaskbar = false;
                    wd.ShowDialog(this);
                    LoadCurrentAlerts();
                }
                else
                    MessageBox.Show("Selecione um alerta para editar!", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception ex)
            {
                HandleException("Iniciar edição do alerta selecionado.", ex);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        private void DeleteSelectedAlert()
        {
            try
            {
                if (lstAlerts.SelectedItems.Count > 0)
                {
                    Cursor = Cursors.WaitCursor;
                    if (MessageBox.Show("Deseja realmente excluir os alertas selecionados?", "Questão", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        BusinessLogic.Configuration bl = new GTA.BusinessLogic.Configuration();
                        foreach (ListViewItem listItem in lstAlerts.SelectedItems)
                            bl.DeleteAlert(Convert.ToInt32(listItem.SubItems[0].Text));

                        MessageBox.Show("Alertas excluídos com sucesso!", "Confirmação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadCurrentAlerts();
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException("Deletar o alerta(s) selecionado(s).", ex);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        private void UpdateAlertState(GTA.BusinessEntity.Configuration.AlertState notificationState)
        {
            try
            {
                if (lstAlerts.SelectedItems.Count == 1)
                {
                    Cursor = Cursors.WaitCursor;
                    new BusinessLogic.Configuration().UpdateAlertState(Convert.ToInt32(lstAlerts.SelectedItems[0].SubItems[0].Text), notificationState);
                    MessageBox.Show("Status atualizado com sucesso!", "Confirmação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadCurrentAlerts();
                }
                else
                    MessageBox.Show("Selecione um alerta para alterar o status!", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception ex)
            {
                HandleException("Atualizar o status do alerta.", ex);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        private void HandleContextMenuItemsState()
        {
            try
            {
                editarToolStripMenuItem.Enabled = lstAlerts.SelectedItems.Count > 0;
                excluirToolStripMenuItem.Enabled = lstAlerts.SelectedItems.Count > 0;
                alterarStatusToolStripMenuItem.Enabled = lstAlerts.SelectedItems.Count > 0;
                toolStripMenuItem1.Enabled = lstAlerts.SelectedItems.Count > 0;

                ativoToolStripMenuItem.Enabled = false;
                inativoToolStripMenuItem.Enabled = false;
                toolStripMenuItem2.Enabled = false;
                if (lstAlerts.SelectedItems.Count == 1)
                {
                    BusinessEntity.Configuration.Alert alert = alerts.Find(it => it.ID.CompareTo(Convert.ToInt32(lstAlerts.SelectedItems[0].SubItems[0].Text)) == 0);
                    if (alert != null)
                    {
                        ativoToolStripMenuItem.Enabled = alert.State == GTA.BusinessEntity.Configuration.AlertState.Inativo;
                        inativoToolStripMenuItem.Enabled = alert.State == GTA.BusinessEntity.Configuration.AlertState.Ativo;
                        toolStripMenuItem2.Enabled = alert.SleepDate != DateTime.MinValue;
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException("Tratar o status do menu de contexto da lista de alertas", ex);
            }
        }
        private void SetAlertSleep(GTA.BusinessEntity.Configuration.AlertSleepType alertSleepType)
        {
            try
            {
                if (lstAlerts.SelectedItems.Count == 1)
                {
                    Cursor = Cursors.WaitCursor;
                    if (MessageBox.Show("Deseja realmente pausar o alerta selecionado?", "Questão", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        new BusinessLogic.Configuration().UpdateAlertSleep(Convert.ToInt32(lstAlerts.SelectedItems[0].SubItems[0].Text), alertSleepType);
                        MessageBox.Show("Alerta pausado com sucesso!", "Confirmação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadCurrentAlerts();
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException("Definir uma pausa para o alerta.", ex);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        private void SetSpecificPauseDate()
        {
            try
            {
                BusinessEntity.Configuration.Alert selectedAlert = alerts.Find(it => it.ID.CompareTo(Convert.ToInt32(lstAlerts.SelectedItems[0].SubItems[0].Text)) == 0);
                if (selectedAlert != null)
                {
                    FrmDateBox wd = new FrmDateBox();
                    wd.ShowDialog(this);
                    if (((DateTime)wd.Tag) != DateTime.MinValue)
                    {
                        BusinessLogic.Configuration bl = new GTA.BusinessLogic.Configuration();
                        bl.UpdateAlertSleep(selectedAlert.ID, (DateTime)wd.Tag);
                        LoadCurrentAlerts();
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException("Definir uma pausa específica para o alerta", ex);
            }
        }
        private void DisablePause()
        {
            try
            {
                BusinessEntity.Configuration.Alert selectedAlert = alerts.Find(it => it.ID.CompareTo(Convert.ToInt32(lstAlerts.SelectedItems[0].SubItems[0].Text)) == 0);
                if (selectedAlert != null)
                {
                    if (CustomMessageBox.CustomMessageBox.Show("Deseja realmente desabilitar a pausa do alerta?", "Questão", CustomMessageBox.CustomMessageBox.CustomMessageBoxButtons.YesNo, CustomMessageBox.CustomMessageBox.CustomMessageBoxIcon.Question) == CustomMessageBox.CustomMessageBox.CustomMessageBoxResult.Yes)
                    {
                        BusinessLogic.Configuration bl = new GTA.BusinessLogic.Configuration();
                        bl.UpdateAlertSleep(selectedAlert.ID, DateTime.MinValue);
                        LoadCurrentAlerts();
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException("Limpar a pausa do alerta", ex);
            }
        }
        #endregion
    }
}
